#include "udp_client.hpp"
#include "Commn.hpp"
#include "Log.hpp"
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
using namespace LogModule;
#include <limits>
#include <signal.h>
int socketfd = -1;
sockaddr_in server;

void ClientQuit(int signo)
{
    (void)signo;
    std::string quit = "QUIT";
    ::sendto(socketfd,quit.c_str(),quit.size(),0,CONV(&server),sizeof(server));   
    exit(0);
}

void* Receive(void* args)
{
    while(true)
    {
        //出现的问题 !!!
        sockaddr_in peer; //这个必须在循环里创建，udp每一个都有独立的数据报，如果是全局的，那么len大小会错误，会导致输出不能正常显示。
        socklen_t len = sizeof(peer);

        char inbuffer[1024];
        int n = ::recvfrom(socketfd,inbuffer,sizeof(inbuffer)-1,0,CONV(&peer),&len);
        std::cout << " n: " << n << std::endl;
        if (n > 0)
        {
            inbuffer[n] = 0;
            std::cerr << inbuffer << std::endl;
        }

    }
    return nullptr;
}

int main(int argc, char *argv[])
{
    if (argc != 3)
    {
        std::cout << "Please use for ./client_udp + ip + port" << std::endl;
        Die(USE_ERROR);
    }

    signal(2,ClientQuit); //处理用户退出
    socketfd = ::socket(AF_INET6, SOCK_DGRAM, 0);

    // char = argv[1];
    std::string ip = argv[1];
    uint16_t port = atoi(argv[2]);
    if (socketfd < 0)
    {
        Die(SOCKET_ERROR);
    }
    LOG(LogLevel::DEBUG) << "socket create success, fd is " << socketfd;
    

    //手动写
    server.sin_family = AF_INET;
    server.sin_addr.s_addr = ::inet_addr(ip.c_str()); 
    server.sin_port = ::htons(port);
    socklen_t len = sizeof(server);

    std::string message;

    pthread_t tid;
    int ret = pthread_create(&tid,nullptr,Receive,nullptr);
    std::cout << " ret: " << ret << std::endl;
    std::string online = " ...来了哈!";
    ::sendto(socketfd,online.c_str(),online.size(),0,CONV(&server),len);

    while(true)
    {
        std::cout << "Please Enter# ";
        getline(std::cin,message);
        // std::cin.ignore(std::numeric_limits<std::streamsize>::max(),'\n');
        ::sendto(socketfd,message.c_str(),message.size(),0,CONV(&server),len);   
    }
    return 0;
}